package com.fzrskj.cloud.free.api;

import com.fzrskj.cloud.free.consts.ApiReturnConstant;
import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.fzrskj.cloud.free.dic.utils.DicParamUtils;
import com.fzrskj.cloud.free.sys.utils.SysRunTimeLogUtils;
import com.fzrskj.cloud.free.user.utils.UserLogUtils;
import ms.core.tool.StrTool;
import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Sms139000.
 *
 * @author zj.
 * Created on 2019/11/12 0012.
 */
public class Sms139000API implements SmsAPI {
    final private String defaultUrl = "http://www.china-sms.com/send/gsend.asp";

    /**
     * 发关短信
     *
     * @param param
     * @return
     */
    @Override
    public String send(String param) {
        String sendparam = "";
        JSONObject obj_result = new JSONObject();
        JSONObject json = JSONObject.fromObject(param);
        String phonenumber = json.getString("Tel");
        String msgContent = json.getString("Content");
        String sendsmsurl = DicParamUtils.getParamValue("hlSmsUrl");
        String account = DicParamUtils.getParamValue("hlUsername");
        String password = DicParamUtils.getParamValue("hlToken");

        //基本参数判断
        if (StrTool.isBlankStr(account) || StrTool.isBlankStr(password)) {
            obj_result.put("code", "-1");
            obj_result.put("message", "接口参数不全");
            return obj_result.toString();
        }

        if ("".equals(phonenumber) || "".equals(msgContent)) {
            obj_result.put("code", "-1");
            obj_result.put("message", "手机号码或短信内容不能为空");
            return obj_result.toString();
        }

        sendsmsurl = StrTool.isBlankStr(sendsmsurl) ? this.defaultUrl : sendsmsurl;

        //参数
        try {
            sendparam += "name=" + account;
            sendparam += "&pwd=" + password;
            sendparam += "&dst=" + phonenumber;
            sendparam += "&msg=" + URLEncoder.encode(msgContent, "GB2312");

            Map<String, Object> request = sendRequest(sendsmsurl, sendparam);
            String errid = request.get("errid").toString();
            String err = request.get("err").toString();
            if (errid.equals("0")){
                obj_result.put(ApiReturnConstant.RESULT_CODE, "0");
                obj_result.put(ApiReturnConstant.RESULT_MSG, "操作成功");
            } else {
                obj_result.put(ApiReturnConstant.RESULT_CODE, "-1");
                obj_result.put(ApiReturnConstant.RESULT_MSG, err);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj_result.toString();
    }

    /**
     * 中间件请求参数
     *
     * @param url    对应接口地址
     * @param param  json 参数
     * @return
     */
    private Map<String, Object> sendRequest(String url, String param) {
        String result = null;
        try {
            result = getUrl(url + "?" + param);
           //result = "num=1&success=17605012011&faile=&err=发送成功！&errid=0";
            System.out.println("result = " + result);
            UserLogUtils.addLog(this, this.getUserId(), Thread.currentThread().getStackTrace()[1].getMethodName(), "发送报文=【" + url + "?" + param + "】,接收报文 【" + result + "】");
        } catch (Exception e) {
            SysRunTimeLogUtils.addLog(this, this.getUserId(), Thread.currentThread().getStackTrace()[1].getMethodName(), "发送报文 =【" + url + "?" + param + "】,接收异常 =【" + e.getMessage() + "】");
        }
        if (result == null || result.length() < 2) {
            result = "err=请求上级失败:请联系管理员&errid=999";
        }
        return resultToMap(result);
    }

    private int getUserId() {
        return null == CloudContextUtils.getSession() ? CloudContextUtils.getAdminId() : CloudContextUtils.getSession().getUID();
    }

    // 返回的字符串转Map
    private Map<String, Object> resultToMap(String result) {
        result = result.replaceAll("\n","");
        String[] resultA = result.split("&");
        String[] tmp;
        Map<String, Object> resultM = new HashMap<>();
        String err = "";
        for (int i = 0; i < resultA.length; i++) {
            String val = resultA[i];
            tmp = val.split("=");
            if (tmp[0].equals("err")) {
                err += tmp[1] + ";";
            } else if (val.length() == (tmp[0].length() + 1)) {
                resultM.put(tmp[0], "");
            } else {
                resultM.put(tmp[0], tmp[1]);
            }
        }
        if (!err.equals("")) {
            resultM.put("err", err);
        }
        return resultM;
    }

    public static void main(String[] a){
        String url="a=0\n";
//        System.out.println(url.replaceAll("\n",""));

        System.out.println(url);
        System.out.print("111");
    }

    private String getUrl(String urlString) {
        StringBuffer sb = new StringBuffer();

        try {
            URL url = new URL(urlString);
            URLConnection conn = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;

            while((line = reader.readLine()) != null) {
                sb.append(line);
            }

            reader.close();
        } catch (IOException var7) {
            System.out.println(var7.toString());
        }

        return sb.toString();
    }
}
